#include "StdAfx.h"
#include "ContactSyncTask.h"
#include "Regesiter.h"
#include <string>
#include "../commonlib/Log.h"

ContactSyncTask::ContactSyncTask(Outlook::_Application* spAppCache){
	m_app = spAppCache;
	//if(!syncer)
	//	syncer = new ContactSync(m_app);
}

ContactSyncTask::ContactSyncTask(void){
}


ContactSyncTask::~ContactSyncTask(void){
	//delete regesiter;
	//delete syncer;
}



void* ContactSyncTask::run(void * param)
{
	while(1){		
		std::wstring serviceProvider;
		std::wstring serviceUri;
		std::wstring userEmail;
		std::wstring reminderPhone;
		bool EnableContact;
		bool EnableReminder;
		try{
			if(regesiter.LoadSyncServiceInfo(serviceProvider,serviceUri,userEmail,reminderPhone,EnableContact,EnableReminder) == ERROR_SUCCESS){
				if(EnableContact){
					ATLASSERT(m_app);
					//std::wstring address;
					//if(m_app->Version.Detach()[1] < '4'){
					//	address = m_app->Session->CurrentUser->Address;
					//}
					//else if(m_app->Version.Detach()[1] == '2' && m_app->Version.Detach()[7] < '6'){
					//	address = m_app->Session->CurrentUser->Address;
					//}
					//for 2010
					//else{
					//	auto objAddressEntry  = m_app->GetNamespace(L"MAPI")->CurrentUser;
					//	auto user = objAddressEntry->AddressEntry->GetExchangeUser();
					//	auto usersmtp = user->PrimarySmtpAddress;
					//	address = (wchar_t*)usersmtp;
					//}
					//
					//!!!!!!we need an object in this thread, not the thread that create it
					//
					LogDebug(_T("Contact begin one Sync operation"));
					ContactSync syncer(m_app);
					//TODO:password is not need
					syncer.Sync(serviceUri,userEmail,L"ekaadmin");
				}		
			}
		}
		catch(...){
			LogDebug(_T("ContactSyncTask Catch unknown Exception"));
		}
#ifdef _DEBUG
		sleep(20000);
#else
		sleep(1000*60*10);
#endif
	}
	return NULL;
}